<template>
  <div class="viewContain">
    <el-form :inline="true" size="small" :model="listQuery">
      <el-row>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
          <el-form-item label-width="100px" label="角色名称">
            <el-input v-model="listQuery.name" size="small" placeholder="输入的角色名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="getList">查询</el-button>
            <el-button type="primary" plain size="mini" @click="reset">重置</el-button>
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }" align="right">
          <el-form-item>
            <el-button type="primary" size="mini" @click="showAddRoleFrom">新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <section>
      <el-table
        v-loading="listLoading"
        :data="tableData"
        border
        :empty-text="empty"
        :height="height"
        size="mini"
      >
        <el-table-column type="index" align="center" label="序号">
          <template slot-scope="scope">
            <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="角色名称" min-width="150px" align="center" />
        <el-table-column prop="parentName" label="父级角色" min-width="150px" align="center" />
        <el-table-column prop="des" label="角色描述" min-width="150px" align="center" />
        <el-table-column label="操作" min-width="200px" align="center">
          <template slot-scope="scope">
            <el-button class="text-button" size="mini" @click="getRoleInfoById(scope.row)">修改</el-button>
            <el-button class="text-button" size="mini" @click="showPermInfoTree(scope.row)">权限</el-button>
            <el-button v-if="scope.row.status==='0'" class="text-button" disabled size="mini" @click="delRoleInfoById(scope.row.id)">删除</el-button>
            <el-button v-if="scope.row.status!=='0'" class="text-button el-button--danger" size="mini" @click="delRoleInfoById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" :total-count="totalCount" @pagination="getList" />
    </section>
    <el-dialog v-loading="dialogLoad" :title="modalTitle" :visible.sync="showAddRoleInfo" :close-on-click-modal="false" :modal-append-to-body="false" width="400px">
      <el-form ref="addRoleForm" :model="addRoleForm" label-width="100px" :rules="addRoleFormRules">
        <el-form-item label="角色名称：" prop="name">
          <el-input v-model="addRoleForm.name" maxlength="10" clearable style="width: 200px;" />
        </el-form-item>
        <el-form-item label="角色描述：" prop="des">
          <el-input v-model="addRoleForm.des" maxlength="20" clearable style="width: 200px;" />
        </el-form-item>
        <el-form-item label="父级角色：" prop="pid">
          <el-select v-model="addRoleForm.pid" placeholder="请选择父级角色" filterable style="width: 200px;">
            <el-option
              v-for="item in parentList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否可以删除">
          <el-radio v-model="addRoleForm.status" label="1">是</el-radio>
          <el-radio v-model="addRoleForm.status" label="0">否</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" size="small" plain @click.native="showAddRoleInfo = false">取消</el-button>
        <el-button type="primary" size="small" @click.native="addSubmit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="'['+ showPermInfoForm.name+']'+modalTitle" :visible.sync="showPermInfo" :close-on-click-modal="false" :modal-append-to-body="false" width="400px">
      <el-form label-width="20px" style="height: 300px; overflow-y: auto;">
        <el-form-item>
          <el-tree
            ref="tree"
            v-loading="treeLoading"
            :data="rosureTreeDate"
            show-checkbox
            default-expand-all
            node-key="id"
            highlight-current
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button size="small" type="primary" plain @click.native="showPermInfo = false">取消</el-button>
        <el-button type="primary" size="small" @click.native="addRolePermSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import pagination from '@c/pagination'
import { getSelectListRoleInfo, insertRoleInfo, updateRoleInfoById, getRolePermInfoByRoleId, saveRolePermInfo } from '@a/core/role.js'
import { getResourceTree } from '@a/core/role.js'
import { commonMixin } from '@v/mixin/commonMixin.js'
import ComApiUrl from '@a/comomApi.js'
export default {
  components: { pagination },
  mixins: [commonMixin],
  data() {
    return {
      comApiUrlList: new ComApiUrl('/core/api/role/getPageRoleList'),
      comApiUrlDelete: new ComApiUrl('/core/api/role/delRoleInfoById/'),
      comApiUrlAdd: new ComApiUrl('/core/api/role/insertRoleInfo'),
      comApiUrlUpdate: new ComApiUrl('/core/api/role/updateRoleInfoById'),
      height: window.innerHeight - 370,
      tableData: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
      parentList: [],
      listLoading: false,
      // 隐藏弹出窗口
      showAddRoleInfo: false,
      dialogLoad: false,
      treeLoading: false,
      showPermInfo: false,
      rosureTreeDate: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      empty: '',
      // 弹出窗口进行 属性校验
      addRoleFormRules: {
        name: {
          required: true,
          validator: (rule, value, callback) => {
            if (value == null || value.length === 0) {
              return callback(new Error('角色名称不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        },
        des: {
          required: true,
          validator: (rule, value, callback) => {
            if (value == null || value.length === 0) {
              return callback(new Error('角色描述不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        },
        pid: {
          required: true,
          validator: (rule, value, callback) => {
            if (value == null || value.length === 0) {
              return callback(new Error('父级角色不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      },
      permRoleId: '',
      permRoleName: '',
      showPermInfoForm: {
        name: '',
        roleId: ''
      },
      modalTitle: '',
      checkFlat: '',
      // 新增界面数据
      addRoleForm: {
        name: '',
        des: '',
        pid: '',
        status: ''
      },

      // 分页数据 开始
      totalCount: 0, // 分页参数
      listQuery: {
        name: '',
        pageNo: 1,
        pageSize: 10
      }
    }
  },
  created() {
    window.onresize = () => {
      this.height = window.innerHeight - 290
    }
    // 在初始化时调用获取角色列表的方法
    // this.listLoading = true;
    this.getList()
    this.getSelectListRoleInfo()
  },
  methods: {
    // 查询所有角色名称和id
    getSelectListRoleInfo() {
      getSelectListRoleInfo().then(res => {
        if (res.data) {
          this.parentList = res.data
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 查询列表的方法
    getList() {
      this.getInfo()
    },
    reset() {
      this.listQuery = {
        name: '',
        pageNo: 1,
        pageSize: 10
      }
      this.getList()
    },
    // 清空FORM表单
    resetForm(formName) {
      if (this.$refs[formName] === undefined) {
        return
      }
      console.log('formName', formName);
      this.$refs[formName].resetFields()
    },
    // 点击【新增】弹出新增界面方法
    showAddRoleFrom() {
      this.addRoleForm = {
        name: '',
        des: '',
        pid: '',
        status: ''
      }
      this.resetForm('addRoleForm')
      this.modalTitle = '角色管理-新增'
      this.checkFlat = '1'
      this.showAddRoleInfo = true
    },
    // 新增、修改弹出窗体信息后点击-保存方法
    addSubmit() {
      if (this.checkFlat === '1') {
        this.addRoleInfo()
      } else {
        this.updateRoleInfoById()
      }
    },
    // 功能新增-保存方法
    addRoleInfo() {
      this.$refs.addRoleForm.validate((valid) => {
        if (valid) {
          const para = Object.assign({}, this.addRoleForm)
          insertRoleInfo(para).then(res => {
            if (res.code === 0) {
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.showAddRoleInfo = false
              this.getList()
            } else if (res.code === -1) {
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    // 点击编辑按纽
    getRoleInfoById(row) {
      console.log('row', row);
      this.resetForm('addRoleForm')
      this.addRoleForm = {
        name: row.name,
        des: row.des,
        pid: row.pid,
        id: row.id,
        status: row.status,
        parentName: row.parentName
      }
      this.modalTitle = '角色管理-修改'
      this.checkFlat = '2'
      this.showAddRoleInfo = true
    },
    //  功能修改 保存方法
    updateRoleInfoById() {
      this.$refs.addRoleForm.validate((valid) => {
        if (valid) {
          const para = Object.assign({}, this.addRoleForm)
          updateRoleInfoById(para).then(res => {
            if (res.code === 0) {
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.showAddRoleInfo = false
              this.getList()
            } else if (res.code === -1) {
              this.$message({
                message: res.msg,
                type: 'warning'
              })
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    // 删除角色信息
    delRoleInfoById(id) {
      this.delete(id)
    },
    // 通过用户ID找到用户对应的角色 开始
    getRolePermInfoById(roleId) {
      getRolePermInfoByRoleId(roleId).then(res => {
        if (res.data) {
          this.$refs.tree.setCheckedKeys(res.data)
        } else {
          this.$refs.tree.setCheckedKeys([])
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 点击权限按纽弹出权限界面 开始
    showPermInfoTree(row) {
      this.treeLoading = true
      this.modalTitle = '角色赋权限'
      this.showPermInfo = true
      this.showPermInfoForm.roleId = row.id
      this.showPermInfoForm.name = row.name
      // 查询资源树形结构  开始
      getResourceTree().then(res => {
        this.treeLoading = false
        if (res.data) {
          this.rosureTreeDate = res.data
          this.getRolePermInfoById(this.showPermInfoForm.roleId)
        }
      }).catch(err => {
        this.treeLoading = false
        console.log(err)
      })
    },
    // 弹出权限窗体信息后点击 保存方法 开始 getCheckedNodes(false,1)选重子节点的跟节点；getCheckedNodes(true,1)中选中跟节点下的子节点；
    addRolePermSubmit() {
      let resId = this.$refs.tree.getCheckedNodes(false, 1).map(item => item.id)
      if (!resId.length) {
        this.$message({
          message: '请至少配置一个权限项',
          type: 'warning'
        })
        return
      }
      resId = resId.join(',')
      const para = {
        resId: resId,
        roleId: this.showPermInfoForm.roleId
      }
      saveRolePermInfo(para).then(res => {
        if (res.code === 0) {
          this.$message({
            message: '提交成功',
            type: 'success'
          })
          this.showPermInfo = false
        } else if (res.code === -1) {
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
<style>

</style>
